﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OracleClient;
using System.Data.SqlClient;
using System.IO;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using INTEX.DataBase;
using INTEXTECH;
using ReflectionStudio.Components.UserControls;
using ReflectionStudio.Core;
using ReflectionStudio.Core.Events;
using ReflectionStudio.Core.Helpers;
using INTEX.DataBase.Tools;
using ReflectionStudio.Controls;
namespace WPFExcelReport
{
    public partial class JLTCAD2ITX : DocumentBase
    {
        #region====================Properties=======================
        ApplicationBase ApplicationBase;
        bool IsSetUp = false;
        DataSet setCADMap = null;
        bool fail = false;
        DataRow LastRow = null;
        string failreason = "";
        string root = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\");
        public OracleConnection OracleDB;
        public IntexReptServBLClient proxy;
        private Dictionary<string, object> dicParamater;
        public SETINTEXDB SetData
        {
            get
            {
                return (SETINTEXDB)TryFindResource("SetData"); ;
            }
        }
        INTEXDBC INTEXDBC;
        bool IsAutoRun = true;
        bool IsRunning = false;
        GB2312Convert8859P1 gb2312;
        public SETINTEXDB Set4ITX
        {
            get
            {
                return (SETINTEXDB)TryFindResource("Set4ITX");
            }
        } 
        CollectionViewSource vwLogInfo
        {
            get
            {
                return (CollectionViewSource)this.FindResource("vwLogInfo");
            }
        }
        DataRow dwLogInfo
        {
            get
            {
                if (vwLogInfo.View == null)
                    return null;
                if ((DataRowView)vwLogInfo.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwLogInfo.View.CurrentItem).Row;
            }
        }
        SETINTEXDB setJLTCAD2ITX = new SETINTEXDB();
        JLTCAD2ITXData m_Data, m_DataX;
        private DataRow dwUI;
        ExcelX.ExcelLib.ExcelAgent m_exAgent;
        DataRow dwBSFARB, dwWASTAMM, dwBHSATZ;
        string UserID = "";
        SqlConnection SqlServerDB;
        DataSet setDISPO = new DataSet();
   
        private string FClothNO
        {
            get
            {
                return txtCADART.Text;
            }
            set
            {
                txtCADART.Text = value;
            }
        }
        private string FInterID
        {
            get
            {
                return txtFInterID.Text;
            }
            set
            {
                txtFInterID.Text = value;
            }
        }
        public JLTCAD2ITX()
        {
            try
            {
                InitializeComponent();
                this.Name = "JLTCAD2ITX";
                this.Title = "JLTCAD2ITX";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        #endregion
        protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
        {
            if (!IsSetUp)
            {
                ApplicationBase.Quit();
            }
            base.OnClosing(e); 
        }
        #region ===================Events========================
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                FInterID = "1"; 
                if (!IsSetUp)
                {
                    ApplicationBase = new ApplicationBase();
                    ApplicationBase.Load();
                    proxy = ApplicationBase.proxy;
                    OracleDB = ApplicationBase.OracleDB;
                    SqlServerDB = new SqlConnection(ApplicationBase.SqlDB);
                    m_Data = new JLTCAD2ITXData(OracleDB, proxy);
                    m_Data.SqlServerDB = SqlServerDB;                   
                    txtUserID.Text = ApplicationBase.User;
                    txtPassword.Password = ApplicationBase.Pwd;
                    ReloadCon();
                }
                INTEXDBC = new INTEXDBC(OracleDB, proxy);
                FClothNO = "S3-236";
                gb2312 = new GB2312Convert8859P1();
                FInterID =m_Data.ReadLog();
                vwLogInfo.View.CurrentChanged += vwLogInfo_CurrentChanged;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }

        void vwLogInfo_CurrentChanged(object sender, EventArgs e)
        {
            if (dwLogInfo == null)
                return;
            if (LastRow == dwLogInfo)
                return;
            LastRow = dwLogInfo;
            m_Data.SetData = SetData;
            m_Data.SetDISPO = setDISPO;
            m_Data.SetCAD = setCADMap;
            try
            {
                DataSet SResult = m_Data.CAD2ITX(dwLogInfo);
                m_Data.WritePFLog("", dwLogInfo);
                Set4ITX.Clear();
                Set4ITX.Merge(SResult);
            }
            catch (Exception ex)
            { 
            }
        } 
        public override void SetUp(Dictionary<string, object> dicParamater)
        {
            try
            {
                using (new LongOperation(this, "读取符合条件的记录"))
                {
                    base.SetUp(dicParamater);
                    this.dicParamater = dicParamater;
                    OracleDB = (OracleConnection)dicParamater["OracleDB"];
                    SqlServerDB = (SqlConnection)dicParamater["SqlServerDB"];
                    proxy = (IntexReptServBLClient)dicParamater["proxy"];
                    m_Data = new JLTCAD2ITXData(OracleDB, proxy);
                    m_Data.SqlServerDB = SqlServerDB; 
                    txtUserID.Text = (string)dicParamater["User"];
                    txtPassword.Password = (string)dicParamater["Pwd"]; 
                    ReloadCon();
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            finally
            {
                IsSetUp = true;
            }
        }
 
        private void btnLogIn_Click(object sender, RoutedEventArgs e)
        {
            string Mandant = txtMANDANT.Text.ToUpper();
            string userID = m_Data.Left(txtUserID.Text.ToUpper() + "        ", 8);
            System.Security.SecureString SPassword = txtPassword.SecurePassword;
            txtLogIn.Background = new SolidColorBrush(Colors.Yellow);
            DataSet setResult = m_Data.LogIn(Mandant, userID, SPassword);
            if (setResult.Tables.Count > 0)
            {
                DataRow dwUser = setResult.Tables[0].Rows[0];
                txtSPRACHKZ.Text = dwUser["HRSPRKZ"].ToString();
                UserID = userID;
                m_Data.UserID = userID;
                this.UserID = userID;

                m_Data.WorkingDate = DateTime.Now.Year.ToString() + m_Data.Right("00" + DateTime.Now.Month.ToString(), 2)
                    + m_Data.Right("00" + DateTime.Now.Day.ToString(), 2);
                m_Data.MANDANT = Mandant;
                m_Data.SPRACHKZ = txtSPRACHKZ.Text.Trim();
                this.txtLogIn.Text = DateTime.Now.ToLocalTime().ToString() + ": " + userID + "已登录";
                txtLogIn.Background = new SolidColorBrush(Colors.Green);

            }
        } 
        private void btnLogInfor_Click(object sender, RoutedEventArgs e)
        {
            LoadJob(FInterID, FClothNO);
        } 

        private void btnAutoRun_Click(object sender, RoutedEventArgs e)
        {
            using (new LongOperation(this, "正在转换"))
            {
                m_Data.IsAutoRun = true;
                m_Data.SetData = SetData;
                m_Data.SetDISPO = setDISPO;
                m_Data.SetCAD = setCADMap;
                m_Data.CheckNewJob();
            }
        }
        #endregion 
   
        public void ReloadCon()
        {
            DataSet setResult = new DataSet();
            setCADMap = new DataSet();
            setDISPO = m_Data.LoadSetDispo("");
            setCADMap.Merge(setDISPO);
            string filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\JLTCADMAPINTEX.XML");
            setResult.ReadXml(filePath);
            setCADMap.Merge(setResult);

            //setCADMap.Merge(setResult, false, MissingSchemaAction.Ignore);
            DataSet setTemp = new DataSet();
            filePath = Path.Combine(PathHelper.ApplicationPath, "Report\\Interface\\FINISHMAPINTEX.XML");
            setTemp.ReadXml(filePath);
            setCADMap.Merge(setTemp);
            setCADMap.Tables["FINISHMAP"].Clear();
            setResult = m_Data.QueryFINISHINGTECHMASTER();
            foreach (DataRow rf in setResult.Tables[0].Rows)
            {
                bool exist = false;
                var query = from DataRow rfc in setCADMap.Tables["FINISHMAP"].AsEnumerable()
                            where rfc["ITXFINISH"].ToString() == rf["FShortCode"].ToString()
                            select rfc;
                foreach (DataRow rq in query)
                {
                    exist = true;
                    rq["CADFINISH"] = rf["FFinishingTechName"];
                    rq["DESCRIPTION"] = rf["FFinishingTechName"];
                    rq["PROCESSFLOW"] = rf["FWholeFinishingName"];
                }
                if (!exist)
                {

                    DataRow rn = setCADMap.Tables["FINISHMAP"].NewRow();
                    rn["ROWID"] = "x";
                    rn["ITXFINISH"] = rf["FShortCode"];
                    rn["CADFINISH"] = rf["FFinishingTechName"];
                    rn["DESCRIPTION"] = rf["FFinishingTechName"];
                    rn["PFID"] = rf["FShortCode"];
                    rn["PROCESSFLOW"] = rf["FWholeFinishingName"];
                    setCADMap.Tables["FINISHMAP"].Rows.Add(rn);
                    //rn["REMARK"] = rf["FWholeFinishingName"];
                }
            }
            m_Data.SetCAD = setCADMap;
            m_Data.SetDISPO = setDISPO;
        } 
        public void LoadJob(string finterid, string FProductNO = "")
        {
            try
            {
                SetData.Clear();
                DataSet setResult = m_Data.QueryLogInfor(finterid, FProductNO);
                SetData.Merge(setResult);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        } 
        private void btnStopRun_Click(object sender, RoutedEventArgs e)
        {
            IsRun.Text = "N";
            m_Data.IsAutoRun = false;
        } 
    }
}